﻿package 
{
	import flash.display.* 
	import flash.events.*; 
	import flash.utils.getTimer;
	
	/**
	 * ...
	 * @author ming
	 */
	public class Main extends Sprite 
	{
		// plane vertex coordinates (and t values) 
		public var x1:Number = -100,    y1:Number = -100,    z1:Number = 0,    t1:Number = 0; 
		public var x2:Number =  100,    y2:Number = -100,    z2:Number = 0,    t2:Number = 0; 
		public var x3:Number =  100,	y3:Number =  100,    z3:Number = 0,    t3:Number = 0; 
		public var x4:Number = -100,    y4:Number =  100,    z4:Number = 0,    t4:Number = 0; 
		public var focalLength:Number = 200;      

		// 2 triangles for 1 plane, _indices will always be the same 
		public var _indices:Vector.<int>; 

		public var _container:Sprite;

		public var _bitmapData:BitmapData; // texture 

		public function Main():void
		{ 
			_indices =  new Vector.<int>();
			_indices.push(0,1,3, 1,2,3);
			_container = new Sprite(); // _container to draw triangles in 
			_container.x = 200; 
			_container.y = 200; 
			addChild(_container);

			{	// load the texture
				var imageLoader:ImageLoader = new ImageLoader("../media/ocean.jpg");
				
				var fn : Function = function (event:Event):void
				{ 
					_bitmapData = imageLoader.bitmap.bitmapData;
					addEventListener(Event.ENTER_FRAME, rotatePlane); 
					
					imageLoader = null;
				}
				
				imageLoader.addEventListener(Event.COMPLETE, fn);
			}
		}

		private function rotatePlane(event:Event):void
		{
			// rotate vertices over time 
			var ticker : Number = getTimer()/400.0; 
			z2 = z3 = -(z1 = z4 = 100*Math.sin(ticker)); 
			x2 = x3 = -(x1 = x4 = 100*Math.cos(ticker)); 

			// calculate t values 
			t1 = focalLength/(focalLength + z1); 
			t2 = focalLength/(focalLength + z2); 
			t3 = focalLength/(focalLength + z3); 
			t4 = focalLength/(focalLength + z4); 

			// determine triangle vertices based on t values 
			var vertices:Vector.<Number> = new Vector.<Number>(); 
			vertices.push(x1*t1, y1*t1, x2*t2, y2*t2, x3*t3, y3*t3, x4*t4, y4*t4);
			// set T values allowing perspective to change 
			// as each vertex moves around in z space
			var uvtData:Vector.<Number> = new Vector.<Number>();
			uvtData.push(0,0,t1, 1,0,t2, 1,1,t3, 0,1,t4);

			// draw
			_container.graphics.clear(); 
			_container.graphics.beginBitmapFill(_bitmapData); 
			_container.graphics.drawTriangles(vertices, _indices, uvtData); 
		}
		
	}
	
}